package com.jdrx.sw.sewage.common.aop;

import com.alibaba.fastjson.JSONObject;
import com.jdrx.sw.sewage.beans.vo.ProcessunitVO;
import com.jdrx.sw.sewage.beans.vo.StorageDeviceVO;
import com.jdrx.sw.sewage.common.enums.StorageDevType;
import com.jdrx.sw.sewage.dao.DevStorageDAO;
import com.jdrx.sw.sewage.dao.DeviceDAO;
import com.jdrx.sw.sewage.dao.ProcessunitDAO;
import com.jdrx.sw.sewage.service.common.RedisService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static com.jdrx.sw.sewage.common.constant.Constant.USE_DEVICE_KEY;

@Aspect
@Component
public class UseDeviceRefreshAop {
    public static final Logger logger = LoggerFactory.getLogger(UseDeviceRefreshAop.class);

    @Autowired
    private DeviceDAO deviceDAO;
    @Autowired
    private ProcessunitDAO processunitDAO;
    @Autowired
    private DevStorageDAO devStorageDAO;
    @Autowired
    private RedisService redisService;

    @Pointcut("@annotation(com.jdrx.sw.sewage.beans.anno.UseDeviceCacheRefresh)")
    public void refreshUseDeviceCache() {
    }

    @After("refreshUseDeviceCache()")
    public void after(JoinPoint joinPoint) {
        logger.info("aop执行,开始刷新已使用设备缓存");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Long stationId = null;
        if (request.getRequestURI().contains("api/devicestorage/scrap"))
            stationId = deviceDAO.findById(Long.valueOf(request.getParameter("devId"))).getStationId();

        if (request.getRequestURI().contains("api/assets/assetsCollect"))
            stationId = Long.valueOf(request.getHeader("stationId"));

        if (null == stationId) {
            logger.info("站点id为空,已使用设备缓存不更新！");
            return;
        }

        Map<String, Object> map = new HashMap<>();
        AtomicInteger storageDeviceNum = new AtomicInteger(0);
        List<ProcessunitVO> sPList = processunitDAO.selectByStationId(stationId);
        Long finalStationId = stationId;
        sPList.stream().forEach(item -> {
            List<StorageDeviceVO> storageDeviceVOS = deviceDAO.selectByStIdAndPId(finalStationId, item.getId());
            storageDeviceVOS.forEach(dev -> {
                dev.setAttachmentNum(devStorageDAO.selectAttachmentNum(StorageDevType.ATTACHMENT.getKey(), dev.getDossierSpec(), dev.getCategoryId(), dev.getMaterielId()));
            });
            map.put(item.getName(), storageDeviceVOS);
            storageDeviceNum.set(storageDeviceNum.get() + storageDeviceVOS.size());
        });
        map.put("storageDeviceNum", storageDeviceNum);
        redisService.setJson(USE_DEVICE_KEY + stationId, new JSONObject(map));
        logger.info("aop结束,已使用设备缓存刷新完成");
    }
}
